const db=require('../db/index')
const bcrypt=require('bcryptjs')
const jwt=require('jsonwebtoken')
const config=require('../config')
exports.login=(req,res)=>{
    db.query('select * from users where email=?',req.body.email,(err,result)=>{
        if(err){
            return req.resSend(401,err)
        }
        if(result.length===0){
            return req.resSend(404,'email输入错误！')
        }
        const compareResult=bcrypt.compareSync(req.body.password,result[0].password)
        if(!compareResult){
            return req.resSend(404,'密码输入错误！')
        }
        const user={...result[0],password:'',user_pic:''}
        const token=jwt.sign(user,config.secretKey,{expiresIn:config.expiresIn})
        res.send({
            status:200,
            msg:'用户登录成功！',
            token:'Bearer '+token
        })
    })
    
}

exports.register=(req,res)=>{
    const userInfo={}
    userInfo.username=req.body.username
    userInfo.password=bcrypt.hashSync(req.body.password,10)
    userInfo.email=req.body.email
    db.query('insert into users set ?',userInfo,(err,result)=>{
       if(err){
        return req.resSend(401,err)
       }
       if(result.affectedRows!==1){
        return req.resSend(404,'用户添加失败！')
       }
       req.resSend(200,'用户添加成功！')
    })
}